#include "remoteCtrl.h"
#include "usart.h"
#include "stdlib.h"
#include "bsp_usart.h"

/**
  * @brief        analysis of the origin data
  * @param[in]    dbusBuf: origin data pointer
  * @param[out]   remoteControl: remote control structure pointer
  * @retval       none
  */
void DbusToRC(volatile const uint8_t *dbusBuf, remoteCtrl_t *remoteControl)
{
    if (dbusBuf == NULL || remoteControl == NULL)
    {
      return;
    }

    remoteControl->rc.ch[0] = (dbusBuf[0] | (dbusBuf[1] << 8)) & 0x07ff;        //!< Channel 0
    remoteControl->rc.ch[1] = ((dbusBuf[1] >> 3) | (dbusBuf[2] << 5)) & 0x07ff; //!< Channel 1
    remoteControl->rc.ch[2] = ((dbusBuf[2] >> 6) | (dbusBuf[3] << 2) |          //!< Channel 2
                                (dbusBuf[4] << 10)) & 0x07ff;
    remoteControl->rc.ch[3] = ((dbusBuf[4] >> 1) | (dbusBuf[5] << 7)) & 0x07ff; //!< Channel 3
    remoteControl->rc.s[0] = ((dbusBuf[5] >> 4) & 0x0003);                       //!< Switch left
    remoteControl->rc.s[1] = ((dbusBuf[5] >> 4) & 0x000C) >> 2;                  //!< Switch right
    remoteControl->mouse.x = dbusBuf[6] | (dbusBuf[7] << 8);                    //!< Mouse X axis
    remoteControl->mouse.y = dbusBuf[8] | (dbusBuf[9] << 8);                    //!< Mouse Y axis
    remoteControl->mouse.z = dbusBuf[10] | (dbusBuf[11] << 8);                  //!< Mouse Z axis
    remoteControl->mouse.pressLeft = dbusBuf[12];                                  //!< Mouse Left Is Press ?
    remoteControl->mouse.pressRight = dbusBuf[13];                                  //!< Mouse Right Is Press ?
    remoteControl->key.v = dbusBuf[14] | (dbusBuf[15] << 8);                    //!< KeyBoard value
    remoteControl->rc.ch[4] = dbusBuf[16] | (dbusBuf[17] << 8);                 //NULL
    //if the channel value is really small, set it to 1024
    remoteControl->rc.ch[0] = (abs(remoteControl->rc.ch[0] - 1024) > 10 ? remoteControl->rc.ch[0] : 1024);
    remoteControl->rc.ch[1] = (abs(remoteControl->rc.ch[1] - 1024) > 10 ? remoteControl->rc.ch[1] : 1024);
    remoteControl->rc.ch[2] = (abs(remoteControl->rc.ch[2] - 1024) > 10 ? remoteControl->rc.ch[2] : 1024);
    remoteControl->rc.ch[3] = (abs(remoteControl->rc.ch[3] - 1024) > 10 ? remoteControl->rc.ch[3] : 1024);

//    printf("%d %d\r\n",  remoteControl->mouse.pressLeft, remoteControl->rc.s[1]);

}


